//index.js
//获取应用实例
import {
  fromNow,
  subStr
} from '../../utils/util';
import {
  apiUrl
} from '../../config';
import {
  find,
  indexOf
} from '../../utils/lodash';

var app = getApp()
let token = null;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    feeds: [],
    user: {},
    loading: false,
    success: true,
    nextPage: 1,
    hasMore: true,
    topicList: [],
    refreshing: false,
    is_admin: false,
    topicList: [{
    topic_cate_id: 0,
    topic_name: "全部"
    }]
  },
  //事件处理函数
  getIndex() {
    wx.request({
      url: apiUrl + '/',
      header: {
        Authorization: token
      },
      success: res => {
        wx.hideLoading();
        if (res.data.code === 1) {
          const data = res.data.data;
          this.setData({
            user: data.user,
            topicList: this.data.topicList.concat(data.topic_list),
            postTopList: data.post_top_list,
            forumInfo: {
              info: data.forum
            },
            is_admin: data.common.is_admin
          });
          // cb();
          wx.setNavigationBarTitle({
            title: data.forum.nickname
          });
          try {
            wx.setStorageSync('alluser', data.user);
          } catch (e) {
            console.log(e)
          }
        }
      }
    });
  },
  loadMore(e) {
    const {
      loading,
      hasMore,
      success
    } = this.data;
    if (loading || !hasMore) {
      return;
    }
    let data = {
      page: this.data.nextPage.toString()
    };
    console.log(this.data);
    if (!!this.data.topic) {
      data.topic_id = this.data.topic;
    }
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: apiUrl + '/post', //仅为示例，并非真实的接口地址
      data,
      header: {
        Authorization: token
      },
      success: (res) => {
        wx.hideLoading()
        switch (Number(res.data.code)) {
          case 1:
            {
              const afterFeeds = res.data.data.data.map(item => {
                item.fromNow = fromNow(item.comment_updateline);
                item.subMessage = subStr(item.message);
                return item;
              });
              this.setData({
                feeds: this.data.feeds.concat(afterFeeds),
                nextPage: this.data.nextPage + 1,
                hasMore: afterFeeds.length >= res.data.data.page.per_page,
                success: true,
                loading: false,
              });
              break;
            }
          default:
            {
              wx.hideLoading()
              this.setData({
                feeds: [],
                success: false,
                loading: false
              });
              break;
            }
        }
      },
      fail: () => {
        wx.hideLoading();
        this.setData({
          feeds: [],
          success: false,
          loading: false
        });
      }
    })
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    // var that = this
    // app.getUserInfo((userInfo) => {
    //   wx.hideLoading()
    //   //更新数据
    //   token = app.globalData.token;
    //   this.loadMore();
    //   this.getIndex();
    //   // that.setData({
    //   //   userInfo: userInfo,
    //   //   feeds: data
    //   // })
    // })
    wx.showLoading({
      title: '加载中',
    });
    app.getUserInfo((userInfo) => {
      wx.hideLoading();
      wx.showShareMenu({
        withShareTicket: true
      });
      //更新数据
      token = app.globalData.token;
      this.loadMore();
      this.getIndex();
      // that.setData({
      //   userInfo: userInfo,
      //   feeds: data
      // })
    })
  },
  onPullDownRefresh() {
    wx.stopPullDownRefresh()
  },
  goDetail(e) {
    wx.showLoading({
      title: '加载中',
    });
    if (e.currentTarget.dataset.node && e.currentTarget.dataset.node == 'go') {
      try {
        console.log(e);
        wx.setStorageSync('feed', e.currentTarget.dataset.feed)
      } catch (e) {
        console.log(e);
      }
      return;
    }
    wx.hideLoading();
    wx.navigateTo({
      url: '/pages/detail/index?threadId=' + e.currentTarget.dataset.feed.thread_id
    });
    console.log('2');
  },
  //点赞
  postLike(e) {
    console.log(e.target);
    const thread_id = e.currentTarget.dataset.id;
    wx.request({
      url: apiUrl + '/post-like', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        thread_id
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function() {
            wx.hideToast()
          }, 2000);
          const afterFeeds = this.data.feeds;
          const user = this.data.user;
          const index = indexOf(afterFeeds, find(afterFeeds, {
            thread_id: thread_id
          }));
          if (index > -1) {
            const userIndex = indexOf(afterFeeds[index].like_list,
              find(afterFeeds[index].like_list, {
                user_id: user.user_id
              }));
            const isLike = afterFeeds[index].user_behavior.is_like;
            afterFeeds[index].user_behavior.is_like = !isLike;
            if (isLike) {
              afterFeeds[index].like_list.splice(userIndex, 1);
              afterFeeds[index].total.likes--;
              afterFeeds[index].likes--;
            } else {
              afterFeeds[index].like_list.push({
                nickname: user.nickname,
                user_id: user.user_id
              });
              afterFeeds[index].total.likes++;
              afterFeeds[index].likes++;
            }
          }
          this.setData({
            feeds: afterFeeds
          });
          app.globalData.feeds = this.data.feeds;
          console.log(app.globalData.feeds);
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  showAcitonSheet(e) {
    console.log(e);
    this.setData({
      feed: e.currentTarget.dataset.feed
    });
    console.log(feed);
    const {
      feed
    } = this.data;
    const {
      thread_id
    } = feed;
    let itemList = this.acitonSheetList();
    console.log(itemList)
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const index = res.tapIndex;
        console.log(typeof index);
        if (typeof index == 'number') {
          switch (itemList[index]) {
            case '删除':
              {
                this.postDelete(thread_id);
                break;
              }
            case '置顶':
              ;
            case '取消置顶':
              {
                this.postTop(thread_id);
                break;
              }
            default:
              ;
          }
        }
        console.log(res)
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },
  acitonSheetList() {
    const menus = [];
    const {
      feed,
      user
    } = this.data;
    if (!!!feed) {
      return menus;
    }
    console.log(menus);
    console.log(user);
    if (!!this.is_admin) {
      menus.push('删除');
      if (!!Number(feed.user_behavior.is_top)) {
        menus.push('取消置顶');
      } else {
        menus.push('置顶');
      }
    }
    if (Number(user.user_id) === Number(feed.author_id) || !!this.is_admin) {
      menus.push('删除');
    } else {
      menus.push('');
    }
    return menus;
  },
  //delete
  postDelete(thread_id) {
    wx.request({
      url: apiUrl + '/post/' + thread_id, //仅为示例，并非真实的接口地址
      method: 'DELETE',
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function() {
            wx.hideToast()
          }, 2000);
          const afterFeeds = this.data.feeds;
          const index = indexOf(afterFeeds, find(afterFeeds, {
            thread_id: thread_id
          }));
          if (index > -1) {
            afterFeeds.splice(index, 1);
          }
          this.setData({
            feeds: afterFeeds
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  postTop(thread_id) {
    const {
      feed,
      postTopList
    } = this.data;
    const type = feed.user_behavior.is_top;
    wx.request({
      url: apiUrl + '/post-stick', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        type,
        thread_id
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function() {
            wx.hideToast()
          }, 2000);
          const afterFeeds = this.data.feeds;
          const index = indexOf(afterFeeds, find(afterFeeds, {
            thread_id: thread_id
          }));
          if (index > -1) {
            if (type == 0) {
              afterFeeds[index].user_behavior.is_top = 1;
              postTopList.push(feed);
            } else {
              afterFeeds[index].user_behavior.is_top = 0;
              const topIndex = indexOf(postTopList, find(postTopList, {
                thread_id: thread_id
              }));
              postTopList.splice(topIndex, 1);
            }
          }
          this.setData({
            feeds: afterFeeds,
            postTopList
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  // 评论
  goComment(e) {
    const feed = e.currentTarget.dataset.feed;
    const index = e.currentTarget.dataset.index;
    wx.showLoading({
      title: '加载中',
    })
    try {
      wx.setStorageSync('feed', feed)
    } catch (e) {
      console.log(e);
    }
    wx.navigateTo({
      url: `/pages/comment/index?thread_id=${feed.thread_id}&index=${index}`
    })
    wx.hideLoading()
  },
  switchTopic(event) {
    this.setData({
      topic: event.target.dataset.topicid
    });
    this.clearList();
    this.loadMore();
  },
  previewPics(e) {
    const all = e.currentTarget.dataset.all;
    const index = e.currentTarget.dataset.current;
    // console.log(index);
    wx.previewImage({
      current: all[index].url, // 当前显示图片的http链接
      urls: all.map(item => item.url) // 需要预览的图片http链接列表
    });
  },
  upper(e) {
    console.log(e);
    this.setData({
      refreshing: true
    });
    setTimeout(() => {
      this.setData({
        refreshing: false
      });
    }, 1000);
  },
  clearList() {
    this.setData({
      feeds: [],
      loading: false,
      nextPage: 1,
      hasMore: true
    });
  }
})
